<template>
    <a-form :form="form" style="height: 100%;">
        <a-tabs v-model="activeKey">
            <a-tab-pane :tab="i18n('form.returnField','返回字段')" key="returnConf" :closable="false">
                <rx-fit style="padding-top: 10px;">
                    <div class="returnFieldBtn">
                        <div class="tableToolBar">
                            <a-button type="primary" @click="selectReturnColumn('query')">
                                {{i18nCustomQuery('isButton.columnHeader','列头设置')}}
                            </a-button>
                            <a-button type="danger" @click="removeReturnFields('query')">
                                {{$ti18('rxList.delBtn','删除')}}
                            </a-button>
                            <a-button type="primary" @click="moveUpReturn('query')">
                                {{$comi18('grid.up','向上')}}
                            </a-button>
                            <a-button type="primary" @click="moveDownReturn('query')">
                                {{$comi18('grid.down','向下')}}
                            </a-button>
                        </div>
                    </div>
                    <rx-grid
                        :columns="returnCols"
                        :dataSource="returnDatas"
                        ref="table_returnConf"
                        :allowRowSelect="true"
                        :multiSelect="true"
                        :showPage="false"
                        :bordered="true"
                        style="height: 90%;"
                    >
                        <span slot="isReturnTitle">
                            <a-checkbox @change="checkAllFields">{{i18n('form.returnField','返回字段')}}</a-checkbox>
                        </span>
                        <span slot="header" slot-scope="{text,record,index}">
                          <a-input v-model="record.header"/>
                        </span>
                    </rx-grid>
                </rx-fit>
            </a-tab-pane>
            <a-tab-pane :tab="i18n('list.queryCondition','查询条件')" key="searchConf" :closable="false" forceRender>
                <rx-fit>
                    <div slot="toolheader" foldbtn="false" border="false">
                        <div class="table-operator">
                            <a-button @click="addSearchRow">{{i18n('list.addConfig','新增条件配置')}}</a-button>
                            <a-button @click="removeRow">{{i18n('list.deleteConfig','删除条件配置')}}</a-button>
                        </div>
                    </div>
                    <rx-grid ref="table_searchConf"
                             :dataSource="searchDatas"
                             :columns="searchCols"
                             :allowRowSelect="true"
                             :multiSelect="true"
                             :showPage="false"
                             :bordered="true"
                    >
                        <span slot="fieldName" slot-scope="{text,record,index}">
                            <a-select v-model="record.fieldName" @change="changeFieldName($event,record)"
                                      :options="fieldDatas"></a-select>
                        </span>
                        <span slot="fieldLabel" slot-scope="{text,record,index}">
                            <a-input v-model="record.fieldLabel"/>
                        </span>
                    </rx-grid>
                </rx-fit>
            </a-tab-pane>
            <a-tab-pane :tab="i18n('list.buttonConfig','按钮配置')" key="buttonConf" :closable="false" forceRender>
                <rx-fit>
                    <div slot="toolheader" foldbtn="false" border="false">
                        <div class="table-operator">
                            <a-button @click="addToolbarRow">{{i18n('list.add','新增')}}{{i18n('list.button','按钮')}}
                            </a-button>
                            <a-button @click="addToolbarAllRows">
                                {{i18n('list.add','新增')}}{{i18n('list.default','默认')}}{{i18n('list.button','按钮')}}
                            </a-button>
                            <a-button @click="removeRow">{{$ti18('rxList.delBtn','删除')}}{{i18n('list.button','按钮')}}</a-button>
                            <a-button @click="upRow">{{i18n('list.upward','向上')}}</a-button>
                            <a-button @click="downRow">{{i18n('list.down','向下')}}</a-button>
                            <a-button @click="topUp">{{ i18n('list.topUp', '置顶') }}</a-button>
                            <a-button @click="bottomUp">{{ i18n('list.bottomUp', '置底') }}</a-button>
                            <a-button @click="joinToolbarRs">{{i18n('list.joinResource','加入权限资源')}}</a-button>
                        </div>
                    </div>
                    <rx-grid
                        ref="table_buttonConf"
                        :dataSource="topBtnsDatas"
                        :columns="topBtnsCols"
                        :allowRowSelect="true"
                        :multiSelect="true"
                        :showPage="false"
                        :bordered="true"
                    >
                        <span slot="eventFunction">
                             {{$ti18('eventFunc', '事件函数', 'apiFormCore')}}
                             <a-tooltip>
                                <template slot="title">
                                    {{i18n('buttonConf.tip1','按钮有2个数据')}}：tree,data <br>
                                    tree:{{i18n('buttonConf.tip2','当前节点的数据')}} <br>
                                    data:{{i18n('buttonConf.tip3','当前节点的父节点')}}data（Objcet）,{{i18n('buttonConf.tip4','如果节点是最上级节点，则返回当前树的全部数据')}}data(Array)
                                </template>
                                 <a-icon type="question-circle" />
                            </a-tooltip>
                        </span>
                        <span slot="btnLabel" slot-scope="{text,record,index}">
                          <a-input v-model="record.btnLabel"/>
                        </span>
                        <span slot="btnName" slot-scope="{text,record,index}">
                          <a-input v-model="record.btnName"/>
                        </span>
                        <span slot="btnClick" slot-scope="{text,record,index}">
                          <a-input v-model="record.btnClick"/>
                        </span>
                        <span slot="btnIcon" slot-scope="{text,record,index}">
                            <rx-input-icon v-model="record.btnIcon" @change="iconChange($event,record)"></rx-input-icon>
                        </span>
                        <span slot="config" slot-scope="{text,record,index}">
                            <a-button v-show="record.needConfig" size="small"
                                      @click="configButton(record)">{{i18n('list.config','配置')}}</a-button>
                            <span v-if="record.isSetedBtn" class="is-seted"><i
                                class="iconfont iconsuccess_fill is-seted"></i>{{i18n('configured','已配')}}</span>
                            <a-icon v-if="record.isSetedBtn" type="delete" style="margin-left: 10px;" @click="clearBtnConfig(record)"/>
                        </span>
                        <span slot="btnShow" slot-scope="{text,record,index}">
                                <a-button size="small" @click="openShowSetting(record)">{{i18n('list.config','配置')}}</a-button>
                                <span v-if="record.isSetedShowCondition" class="is-seted"><i
                                    class="iconfont iconsuccess_fill is-seted"></i>{{i18n('configured','已配')}}</span>
                                <a-icon v-if="record.isSetedShowCondition" type="delete" style="margin-left: 10px;" @click="clearBtnShowCondition(record)"/>
                        </span>
                    </rx-grid>
                </rx-fit>
            </a-tab-pane>
            <a-tab-pane :tab="i18n('list.pageDefine','页面JS函数定义')" key="funConf" :closable="false" forceRender>
                <rx-fit>
                    <div style="height: 100%;overflow: hidden">
                        <rx-monaco-editor
                            ref="bodyScript"
                            v-model="bodyScript"
                            language="javascript"
                            style="height: 500px "
                        >
                            <template v-slot:monacoeditor>
                              <a-dropdown>
                                <a-menu slot="overlay">
                                  <template v-for="item in scriptInsertAry">
                                    <a-menu-item :key="item.clickEvent" v-if="!item.children"
                                                 @click="handInsertScript(item)"
                                    > {{item.name}}
                                    </a-menu-item>

                                    <a-sub-menu :key="item.name" v-if="item.children && item.children.length>0">
                                      <span slot="title">{{item.name}}</span>
                                      <a-menu-item :key="subItem.name" v-for="subItem in item.children"
                                                   @click="handInsertScript(subItem)">
                                        {{subItem.name}}
                                      </a-menu-item>
                                    </a-sub-menu>
                                  </template>
                                </a-menu>
                                <a-button type="primary" style="margin-left: 8px">
                                  {{i18n('list.insertScript','插入脚本')}}
                                  <a-icon type="down"/>
                                </a-button>
                              </a-dropdown>
                              <rx-common-script @select="insertScript" category="插入函数" use-to="list-pcJs" type="0" >
                                <template v-slot:button>
                                  <a-button type="primary" style="margin-left: 8px">
                                    {{i18n('list.insertCode','插入代码')}}
                                    <a-icon type="down"/>
                                  </a-button>
                                </template>
                              </rx-common-script>
                            </template>

                        </rx-monaco-editor>
                    </div>
                </rx-fit>
            </a-tab-pane>
        </a-tabs>
    </a-form>
</template>

<script>
    import {BaseForm, RxGrid, RxFit, RxMonacoEditor,Dialog,Util} from "@lowcode/jpaas-common-lib"
    import FormBoListApi from '@/api/form/core/formBoList'
    import FormBoListTreeEdit2 from '@/api/form/core/formBoListTreeEdit2'
    import rxInputIcon from '@/components/rxComponent/rx-input-icon';
    import reloadColumnDialog from "@/views/modules/form/core/listLayout/reloadColumnDialog";


    export default {
        name: "FormBoListTreeEdit2",
        mixins: [BaseForm, FormBoListTreeEdit2],
        components: {
            RxGrid,
            RxFit,
            RxMonacoEditor,
            rxInputIcon
        },
        computed:{
            returnDatas(){
                return this.fieldsJson.filter(item=>{
                        return item.isReturn==true;
                    })
            }
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "formBoListDialog", key);
            },
            i18nCustomQuery(name, text, key) {
                return this.$ti18(name, text, "formCustomQuery", key);
            },
            get(id) {
                return FormBoListApi.get(id);
            },
            save(values) {
                values.isTreeDlg = "YES";
                values.fieldsJson = JSON.stringify(this.fieldsJson);
                values.searchJson = JSON.stringify(this.searchDatas);
                values.topBtnsJson = JSON.stringify(this.topBtnsDatas);
                values.bodyScript = this.bodyScript;
                //新增时保存应用ID
                let appId = this.curApp.appId;
                if (appId && !this.pkId) {
                    values.appId = appId;
                }
                return FormBoListApi.save(values);
            },
            onload_(values) {
                if (values) {
                    this.fieldsJson=JSON.parse(values.fieldsJson);

                    if (values.searchJson) {
                        this.searchDatas = JSON.parse(values.searchJson);
                    }
                    if (values.topBtnsJson) {
                        this.topBtnsDatas = JSON.parse(values.topBtnsJson);
                    }
                    this.bodyScript = values.bodyScript;
                    this.fieldDatas = this.fieldsJson.map(field => {
                        return {label: field.header, value: field.field, key: field.dataType}
                    });
                    this.reloadTopBtnCols(values);
                }
            },
            handleSubmit(self, this_, callback) {

                this_.form.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    values.pkId = this_.pkId;
                    this.confirmLoading = true;
                    if (this_.validForm) {
                        var flag = this_.validForm(values);
                        if (!flag) {
                            return;
                        }
                    }
                    //校验是否有返回字段。
                    let aryReturnFields= this_.fieldsJson.filter(item=>item.isReturn==true);
                    if(aryReturnFields.length==0){
                        this_.$message.warn(this_.i18n("form.tipInfoRtnFields","请选择返回字段!"));
                        return;
                    }
                    this_.save(values).then(res => {
                        if (res.success && res.code == 200) {
                            if (callback) {
                                callback();
                            }
                            //Util.closeWindow(this_,"ok");
                        }
                    }).catch(() => {
                        this_.$message.error(this.$ti18('rxMsa.sysError','系统错误，请稍后再试!'))
                    }).finally(() => {
                        this_.confirmLoading = false
                    })
                })
            },
            selectReturnColumn() {
                var self_=this;
                FormBoListApi.reloadColumns(this.pkId,false).then(res => {
                    let queryColumnData=res.data
                    let conf = {
                        component: reloadColumnDialog,
                        title:  self_.i18nCustomQuery('isButton.columnHeader','列头设置'),
                        curVm: this,
                        data: {reloadFields: queryColumnData},
                        widthHeight: ['800px', '600px']
                    };
                    Util.open(conf, function (action,data) {
                        if (action != 'ok') {
                            return;
                        }
                        for(let i=0;i<data.length;i++){
                            let row=data[i];
                            let field=row.field;
                            let aryField=self_.fieldsJson.filter(item=>{
                                return item.field==field;
                            });
                            if(aryField.length==1){
                                aryField[0].isReturn=true;
                            }
                        }
                    });
                });

            },
            removeReturnFields() {
                let rows=this.$refs["table_" + this.activeKey].getSelectedRows();
                let self_=this;
                for(let row of rows){
                    let field=row.field;
                    let aryField=self_.fieldsJson.filter(item=>{
                        return item.field==field;
                    });
                    if(aryField.length==1){
                        aryField[0].isReturn=false;
                    }
                }
            },
            moveUpReturn(id) {
                this.$refs["table_" + this.activeKey].moveUp();
            },
            moveDownReturn(id) {
                this.$refs["table_" + this.activeKey].moveDown();
            },
        }
    }
</script>

<style scoped>
.is-seted {
    color: #70B90B;
    margin-left: 5px;
}
</style>